package cn.apotato.inclusion.listener;

import cn.apotato.inclusion.commin.annotation.Inclusion;
import cn.apotato.inclusion.commin.enums.InclusionStrategy;
import cn.apotato.inclusion.commin.response.ResponseData;
import cn.apotato.inclusion.commin.response.ResponseMessage;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 使用 ResponseBodyAdvice 拦截Controller方法默认返回参数，统一处理返回值/响应体
 * @author xphu
 * @version 1.0
 * @date 2021/8/6 14:09
 */
@RestControllerAdvice
public class RestControllerListener implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object response, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 返回了协议，直接返回原始对象
        if (null != response && ResponseMessage.class.isAssignableFrom(response.getClass())) {
            return ((ResponseMessage) response).build();
        }

        Inclusion annotation = Objects.requireNonNull(methodParameter.getMethod()).getAnnotation(Inclusion.class);

        if (annotation == null){
            return response;
        }
        /**
         * 拿到注解上的key和val策略
         */
        String key = annotation.key();
        InclusionStrategy inclusion = annotation.value();

        // 仅在请求成功时进行填充处理
        final HttpServletResponse servletResponse = ((ServletServerHttpResponse) serverHttpResponse).getServletResponse();
        final int status = servletResponse.getStatus();
        if (status >= HttpServletResponse.SC_OK && status < HttpServletResponse.SC_MULTIPLE_CHOICES) {
            return ResponseData.success(key, response, inclusion).dateTime().build();
        }
        return ResponseData.fail(key, response, inclusion).build();
    }
}
